package com.bite.blog.common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class AutotestUtils {
    public static EdgeDriver driver;

    //创建驱动对象
    public static EdgeDriver createDriver() {
        if (driver == null) {
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            //允许访问所有的链接
            options.addArguments("--remote-allow-origins=*");
            driver = new EdgeDriver(options);
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3000));
        }
        return driver;
    }

    public AutotestUtils(String url) {
        EdgeDriver driver = createDriver();
        driver.get(url);
    }

    public List<String> getTime() {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat sim2 = new SimpleDateFormat("yyyyMMdd");
        String filename = sim1.format(System.currentTimeMillis());
        String dirname = sim2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return list;
    }

    /**
     * 获取屏幕截图，把所有的⽤例执⾏的结果保存下来
     */
    public void getScreenShot(String str) throws IOException {
        String original =str;
        String replaced = original.replace('.', '/');  // 替换字符
        List<String> list = getTime();
        String filename =
                "./src/test/java/com/bite/blog/photo/" + list.get(0) + "/"  + list.get(1) + ".png";
        File srcfile = driver.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcfile, new File(filename));
    }
}

